from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

# Create your views here.
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from rest_framework.response import Response
from rest_framework.views import APIView

from app.models import User


@method_decorator(csrf_exempt, name='dispatch')
class UserView(View):

    def get(self,  request, *args, **kwargs):

        user_id = kwargs.get('id')

        if user_id:
            user_val = User.objects.filter(pk=user_id).values('username', 'password', 'gender').first()

            if user_val:
                return JsonResponse({
                    'status': 200,
                    'message': '查询单个用户成功',
                    'results': user_val
                })
            else:
                user_objects_all = User.objects.all().values("username", "password", "gender")
                if user_objects_all:
                    return JsonResponse({
                        'status': 200,
                        'message': '查询所有用户成功',
                        'results': list(user_objects_all)
                    })
            return JsonResponse({
                'status': 400,
                'message': '查询所有用户失败'
            })

    def post(self, requeset, *args, **kwargs):
        username = requeset.POST.get('username')
        pwd = requeset.POST.get('password')
        try:
            user_obj = User.objects.create(username=username, password=pwd)
            return JsonResponse({
                'status': 200,
                'message': '新增单个用户成功',
                'result': {'username': user_obj.username, "gender": user_obj.gender}
            })
        except:
            return JsonResponse({
                'status': 400,
                'message': '新增失败'
            })

    def put(self, request, *args, **kwargs):
        return HttpResponse('put OK')

    def delete(self, requset, *args, **kwargs):
        user_id = kwargs.get('id')
        try:
            user = User.objects.filter(pk=id)
            user.delete()
            return JsonResponse({
                'status': 200,
                'message': '删除成功'
            })
        except:
            return JsonResponse({
                'status': 400,
                'message': '删除失败'
            })



class StudentAPIView(APIView):

    def get(self, request, *args, **kwargs):
        print('DRF GET VIEW')
        return Response('DRF GET VIEW')

    def post(self, *args, **kwargs):
        print('DRF POST VIEW')
        return Response('DRF POST VIEW')